/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.improvement.approval;

import com.alibaba.fastjson.JSONObject;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.improvement.bean.Assessment;
import com.koron.improvement.bean.AssessmentHistory;
import com.koron.improvement.bean.AssessmentItem;
import com.koron.improvement.bean.AssessmentItemHistory;
import com.koron.improvement.mapper.AssessmentHistoryMapper;
import com.koron.improvement.mapper.AssessmentItemHistoryMapper;
import com.koron.improvement.mapper.AssessmentItemMapper;
import com.koron.improvement.mapper.AssessmentMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class AssessmentAuditService implements AfterApprovalService {

    private static final Logger logger = LoggerFactory.getLogger(AssessmentAuditService.class);

    List<AssessmentItem> translateHistoryToItemList(List<AssessmentItemHistory> historyList, String assessmentId) throws Exception {
        List<AssessmentItem> items = new ArrayList<>();
        if (historyList == null || historyList.isEmpty()) {
            return null;
        }
        for (AssessmentItemHistory history : historyList) {
            AssessmentItem item = new AssessmentItem();
//            BeanUtils.copyProperties(item, history);
            item.setItemName(history.getItemName());
            item.setItemId(history.getItemId());
            item.setDeductedScore(history.getDeductedScore());
            item.setDeductedReason(history.getDeductedReason());
            item.setAddUser(history.getAddUser());
            item.setUpdateUser(history.getUpdateUser());
            item.setAddTime(history.getAddTime());
            item.setUpdateTime(history.getUpdateTime());
            item.setAddUserName(history.getAddUserName());
            item.setUpdateUserName(history.getUpdateUserName());
            item.setId(DefaultIdGenerator.getInstance().generateLongId());
            item.setAssessmentId(assessmentId);
            items.add(item);
        }
        return items;
    }

    @Override
    public void editApproval(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        AssessmentHistoryMapper historyMapper = factory.getMapper(AssessmentHistoryMapper.class);
                        AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
                        AssessmentItemHistoryMapper itemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);
                        AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
                        AssessmentHistory history = historyMapper.selectByPrimaryKey(planId);
                        if (history != null) {
                            Assessment assessment = mapper.selectByPrimaryKey(history.getBackupId());
                            List<AssessmentItemHistory> itemHistoryList = itemHistoryMapper.queryListByAssessmentId(history.getId());
                            history.setState(0);
                            historyMapper.updateByPrimaryKeySelective(history);
                            if (null != assessment){
                                assessment.setState(0);
                                mapper.updateByPrimaryKey(assessment);
                            }
                            if (itemHistoryList != null && !itemHistoryList.isEmpty()) {
                                List<AssessmentItem> itemList = translateHistoryToItemList(itemHistoryList, assessment.getId());
                                itemMapper.insertList(itemList);
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void discardApproval(Audit audit) {

    }

    @Override
    public void processDiscard(Audit audit) {
        SessionFactory factory = new SessionFactory();
        try {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            if (idList != null && !idList.isEmpty()) {
                for (String planId : idList) {
                    if (StringUtils.isNotEmpty(planId)) {
                        AssessmentHistoryMapper historyMapper = factory.getMapper(AssessmentHistoryMapper.class);
                        AssessmentMapper mapper = factory.getMapper(AssessmentMapper.class);
                        AssessmentItemHistoryMapper itemHistoryMapper = factory.getMapper(AssessmentItemHistoryMapper.class);
                        AssessmentItemMapper itemMapper = factory.getMapper(AssessmentItemMapper.class);
                        AssessmentHistory history = historyMapper.selectByPrimaryKey(planId);
                        if (history != null) {
                            history.setState(4);
                            historyMapper.updateByPrimaryKeySelective(history);
                            Assessment assessment = mapper.selectByPrimaryKey(history.getBackupId());
                            if (assessment != null) {
                                assessment.setState(5);
                                mapper.updateByPrimaryKeySelective(assessment);
                            }
                        }
                    }
                }
            }
            factory.close();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
        }
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
